package business;

import entity.Event;
import entity.WeatherAlert;
import entity.WeatherForecast;
import gui.WeatherAlertBean;
import java.io.Serializable;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.xml.ws.http.HTTPException;

@Stateless
public class WeatherForecastService implements Serializable {

    @EJB
    private WeatherForecastRetriever forecastRetriever;

    public WeatherAlert getWeatherAlert(Event event) {
        WeatherAlert weatherAlert = null;
        forecastRetriever.setResourceURL(WeatherForecastRetriever.fiveDaysForecasts);
        try {
            WeatherForecast forecast = forecastRetriever.getForecast(event.getCity(),
                    event.getCountry(), event.getDate());
            if (forecast != null && forecast.isBad(event.getBadWeatherThreshold())) {
                weatherAlert = new WeatherAlert();
                weatherAlert.setEvent(event);
                weatherAlert.setForecast(forecast);
            }
        } catch (HTTPException ex) {
            Logger.getLogger(WeatherAlertBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(WeatherAlertBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return weatherAlert;
    }

    public Date getNextSuitableDate(Event event) {
        forecastRetriever.setResourceURL(WeatherForecastRetriever.fiveDaysForecasts);
        Date nextGoodDay = forecastRetriever.getNextGoodConditionsDay(event.getCity(),
                event.getCountry(), event.getDate(), event.getBadWeatherThreshold());
        if (nextGoodDay == null) {
            forecastRetriever.setResourceURL(WeatherForecastRetriever.sixteenDaysForecasts);
            nextGoodDay = forecastRetriever.getNextGoodConditionsDay(event.getCity(),
                event.getCountry(), event.getDate(), event.getBadWeatherThreshold());
        }
        return nextGoodDay;
    }
}
